package com.wms.controller;

import com.wms.common.Result;
import com.wms.entity.Company;
import com.wms.service.CompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/company")
public class CompanyController {

    @Autowired
    private CompanyService companyService;

    // 获取所有公司信息
    @GetMapping("/list")
    public Result<List<Company>> list() {
        List<Company> companies = companyService.list();
        System.out.println("Retrieved Companies: " + companies);
        return Result.suc("获取成功", companies);
    }


    // 通过ID获取公司信息
    @GetMapping("/{id}")
    public Result<Company> getById(@PathVariable Integer id) {
        Company company = companyService.getById(id);
        if (company != null) {
            return Result.suc("获取成功", company);
        } else {
            return Result.fail("公司不存在");
        }
    }

    // 新增公司信息
    @PostMapping("/add")
    public Result<?> add(@RequestBody Company company) {
        try {
            // 检查必填字段
            if (company.getCompanyName() == null || company.getPortId() == null ||
                    company.getManagerName() == null || company.getContactNumber() == null ||
                    company.getStorageFeeRate() == null) {
                return Result.fail("缺少必填字段");
            }

            boolean saveSuccess = companyService.save(company);
            if (saveSuccess) {
                return Result.suc("新增成功");
            } else {
                return Result.fail("新增失败");
            }
        } catch (Exception e) {
            // 打印详细的错误日志
            e.printStackTrace();
            return Result.fail("服务器内部错误: " + e.getMessage());
        }
    }


    // 更新公司信息
    @PutMapping("/update")
    public Result<?> update(@RequestBody Company company) {
        boolean updateSuccess = companyService.updateById(company);
        if (updateSuccess) {
            return Result.suc("更新成功");
        } else {
            return Result.fail("更新失败");
        }
    }

    // 删除公司信息
    @DeleteMapping("/delete/{id}")
    public Result<?> delete(@PathVariable Integer id) {
        boolean removeSuccess = companyService.removeById(id);
        if (removeSuccess) {
            return Result.suc("删除成功");
        } else {
            return Result.fail("删除失败");
        }
    }
}
